package com.qaml.mes.device.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import feign.RequestTemplate;
import feign.codec.EncodeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import java.lang.reflect.Type;
import org.springframework.beans.factory.ObjectFactory;
/**
 * @ClassName FeignClientEncoder
 * @Description 编码
 * @Author leikai
 * @Date 2023/11/16 17:26
 * @Version 1.0
 */
public class FeignClientEncoder extends SpringEncoder {

    private static Logger log = LoggerFactory.getLogger(FeignClientEncoder.class);


    public FeignClientEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        super(messageConverters);
    }

    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {

        try {
            super.encode(object, bodyType, template);
            template.body(ObjectMapperUtil.objectMapper.writeValueAsString(object));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static class ObjectMapperUtil {

        public static ObjectMapper objectMapper=new ObjectMapper();
        static {
            objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
            objectMapper.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL);
        }
    }
}